const { Order, Car, User, Review } = require('../models');
const mongoose = require('mongoose');
const moment = require('moment');

exports.createOrder = async (req, res) => {
    try {
        const userId = req.user.userinfo.id;

        // 再次检查用户实名认证状态
        const user = await User.findById(userId).populate('verification');
        if (!user.isVerified || !user.verification || !user.verification.signature) {
            return res.status(403).json({
                success: false,
                message: '请先完成实名认证并上传电子签名'
            });
        }

        const {
            carId,
            startTime,
            endTime,
            pickupLocation,
            returnLocation,
            additionalServices = [],
            totalAmount,
            rentalFee,
            insuranceFee,
            deposit
        } = req.body;

        // 检查车辆状态
        const car = await Car.findById(carId);
        if (!car || car.status !== '可租') {
            return res.status(400).json({
                success: false,
                message: '车辆不可租用'
            });
        }

        // 生成订单号
        const date = new Date();
        const timestamp = date.getTime().toString().slice(-8);
        const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
        const orderNumber = `ORDER${date.getFullYear()}${(date.getMonth() + 1).toString().padStart(2, '0')}${date.getDate().toString().padStart(2, '0')}${timestamp}${random}`;

        // 创建订单
        const order = await Order.create({
            orderNumber,
            userId,
            carId,
            startTime,
            endTime,
            pickupLocation,
            returnLocation,
            additionalServices,
            totalAmount,
            rentalFee,
            insuranceFee,
            deposit
        });

        // 更新车辆状态
        await Car.findByIdAndUpdate(carId, {
            status: '已租',
            $inc: { 'rentalHistory.rentCount': 1 }
        });

        res.status(201).json({
            success: true,
            message: '订单创建成功',
            data: order
        });

    } catch (error) {
        console.error('创建订单错误:', error);
        res.status(500).json({
            success: false,
            message: '创建订单失败',
            error: error.message
        });
    }
};

// 获取订单列表
exports.getOrders = async (req, res) => {
    try {
        const userId = req.user.userinfo.id;
        const { status, page = 1, limit = 10 } = req.query;

        // 构建查询条件
        const query = { userId };
        if (status) {
            query.status = status;
        }

        // 执行查询
        const orders = await Order.find(query)
            .populate('carId', 'brand model coverImage')
            .skip((page - 1) * limit)
            .limit(parseInt(limit))
            .sort({ createdAt: -1 });

        // 获取总数
        const total = await Order.countDocuments(query);

        res.status(200).json({
            success: true,
            data: {
                orders,
                pagination: {
                    total,
                    page: parseInt(page),
                    limit: parseInt(limit),
                    pages: Math.ceil(total / limit)
                }
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取订单列表失败',
            error: error.message
        });
    }
};

// 获取订单详情
exports.getOrder = async (req, res) => {
    try {
        const { id } = req.params;
        const userId = req.user.userinfo.id;

        const order = await Order.findOne({ _id: id, userId })
            .populate('carId', 'brand model coverImage specifications')
            .populate('userId', 'username phone')
            .lean(); // 使用 lean() 获取普通 JS 对象，方便添加属性

        if (!order) {
            return res.status(404).json({
                success: false,
                message: '订单不存在'
            });
        }

        // 检查订单是否已评价
        const review = await Review.findOne({ orderId: order._id }).select('_id').lean(); // 只选择 reviewId
        if (review) {
            order.isReviewed = true;
            order.reviewId = review._id; // 添加 reviewId
        } else {
            order.isReviewed = false;
        }

        res.status(200).json({
            success: true,
            data: order
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取订单详情失败',
            error: error.message
        });
    }
};

// 续租订单
exports.extendRental = async (req, res) => {
    try {
        const { id } = req.params;
        const { extendDays } = req.body;
        const userId = req.user.userinfo.id;

        // 验证续租天数
        if (!extendDays || extendDays <= 0) {
            return res.status(400).json({
                success: false,
                message: '续租天数必须大于0'
            });
        }

        // 查找订单
        const order = await Order.findOne({
            _id: id,
            userId,
            status: '进行中'
        });

        if (!order) {
            return res.status(404).json({
                success: false,
                message: '订单不存在或无法续租'
            });
        }

        // 计算新的结束时间和费用
        const newEndTime = moment(order.endTime).add(extendDays, 'days').toDate();
        const additionalFee = order.rentalFee / order.rentalDays * extendDays;

        // 更新订单
        order.endTime = newEndTime;
        order.rentalFee += additionalFee;
        order.totalAmount += additionalFee;
        await order.save();

        res.status(200).json({
            success: true,
            message: '续租成功',
            data: {
                newEndTime,
                additionalFee,
                totalAmount: order.totalAmount
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '续租失败',
            error: error.message
        });
    }
};

// 完成订单
exports.completeOrder = async (req, res) => {
    try {
        const { id } = req.params;
        const userId = req.user.userinfo.id;

        // 查找并更新订单
        const order = await Order.findOne({
            _id: id,
            userId,
            status: '进行中'
        });

        if (!order) {
            return res.status(404).json({
                success: false,
                message: '订单不存在或无法完成'
            });
        }

        // 更新订单状态
        order.status = '已完成';
        await order.save();

        // 更新车辆状态
        await Car.findByIdAndUpdate(order.carId, {
            status: '可租'
        });

        res.status(200).json({
            success: true,
            message: '订单已完成'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '完成订单失败',
            error: error.message
        });
    }
};

// 取消订单（简化版，移除事务）
exports.cancelOrder = async (req, res) => {
    try {
        const { id } = req.params;
        const userId = req.user.userinfo.id;

        // 查找订单
        const order = await Order.findOne({
            _id: id,
            userId,
            status: '进行中'  // 只能取消进行中的订单
        });

        if (!order) {
            return res.status(404).json({
                success: false,
                message: '订单不存在或无法取消'
            });
        }

        // 更新订单状态
        order.status = '已取消';
        await order.save();

        // 更新车辆状态
        await Car.findByIdAndUpdate(order.carId, {
            status: '可租'
        });

        res.status(200).json({
            success: true,
            message: '订单取消成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '取消订单失败',
            error: error.message
        });
    }
}; 